import { fetchDetailCustomBySlotId } from "@/services/basiccapacity";
import { userTypeList } from "@/services/geographic";
import { doRobotList } from "@/services/robotManagement";
import { Form, message, Modal, Select, Icon } from "antd";
import React from "react";
import AnswerUtils from "./answerUtils";

//slotData 是选择的词槽
//slotDetailList 是根据选择的词槽查询出来的实体的核心词
//slotValues 是最终提交的词槽数据
class UpdateAnswerModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      appList: [],
      userTagList: [],
      appCheckList: [{ robotId: 'all', robotName: '全部应用' }],
      userTagCheckList: [{ id: 'all', tagName: '全部标签' }],
      type: 'add',
      answerIndex: 0,
      slotDetailList: [],
      slotValues: []
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  }

  openModal = (type, item, index) => {
    this.getAppList()
    this.getUserList()
    const { slotData } = this.props;
    if (slotData && slotData.length > 0) {
      this.getSlotList(type)
    };
    this.setState({ visible: true, type }, () => {
      if (type === 'edit') {
        this.setAnswerInfo(item, index)
      }
    })
  }

  //编辑打开的弹窗，进行赋值
  setAnswerInfo = (item, index) => {
    this.setState({ answerIndex: index }, () => {
      // console.log(item);
      let appCheckList = item.robotList;
      let userTagCheckList = item.userTagIdList;
      if (item.userTagIdList.length === 0) {
        userTagCheckList = [{ id: 'all', tagName: '全部标签' }]
      };
      if (item.robotList.length === 0) {
        appCheckList = [{ robotId: 'all', robotName: '全部标签' }]
      };
      this.AnswerUtilsByModal.setAnswers(item)
      // console.log(userTagCheckList, appCheckList);
      this.setState({ userTagCheckList, appCheckList, slotValues: item.slotValues })
    })
  }

  //获取词槽核心词
  getSlotList = async (type) => {
    const { slotData } = this.props;
    // console.log(slotData);
    const ids = slotData.map(item => item.id);
    const res = await fetchDetailCustomBySlotId({ ids })
    this.setState({ slotDetailList: res }, () => {
      if (type === 'add') {
        //新增 则需要每一个都默认选中全部词槽
        let slotValues = []
        for (const item of res) {
          if (item.isEnum) {
            slotValues.push({ id: item.id, keyName: item.keyName, slotName: item.name, values: ['全部词槽'] })
          }
        };
        this.setState({ slotValues })
      }
    })
  }

  //获取应用列表
  getAppList = async () => {
    const res = await doRobotList({ current: 1, size: 999999 })
    this.setState({ appList: res ? res : [] })
  }

  //获取用户标签列表
  getUserList = async () => {
    const res = await userTypeList({ current: 1, size: 999999 });
    this.setState({ userTagList: res.records ? res.records : [] })
  }

  //选择用户标签
  changeTag = (values, option) => {
    if (values.indexOf('all') != -1) {
      this.setState({ userTagCheckList: [{ id: 'all', tagName: '全部标签' }] })
    } else {
      let userTagCheckList = []
      for (const item of option) {
        const itemInfo = item.props.item;
        // console.log(itemInfo);
        userTagCheckList.push({ id: itemInfo.id, tagName: itemInfo.tagName })
      };
      this.setState({ userTagCheckList })
    }
  }

  //选择应用名称
  changeApp = (values, option) => {
    if (values.indexOf('all') != -1) {
      this.setState({ appCheckList: [{ robotId: 'all', robotName: '全部应用' }] })
    } else {
      let appCheckList = [];
      for (const item of option) {
        const itemInfo = item.props.item
        appCheckList.push({ robotId: itemInfo.robotId, robotName: itemInfo.name })
      };
      this.setState({ appCheckList })
    }
  }

  //选择词槽
  changeSlot = (values, option, slot) => {
    const { slotValues } = this.state;
    //1.判断当前操作的词槽是否存在，存在则修改当前词槽的values值，不存在则push
    const slotIndex = slotValues.findIndex(item => item.id === slot.id);
    if (slotIndex === -1) {
      if (values.indexOf('全部词槽') === -1) {
        slotValues.push({ id: slot.id, keyName: slot.keyName, slotName: slot.name, values })
      } else {
        slotValues.push({ id: slot.id, keyName: slot.keyName, slotName: slot.name, values: ['全部词槽'] })
      }
    } else {
      if (values.indexOf('全部词槽') === -1) {
        slotValues[slotIndex].values = values
      } else {
        slotValues[slotIndex].values = ['全部词槽']
      }
    };
    this.setState({ slotValues })
  }

  //确定
  okModal = async () => {
    const answerResult = await this.AnswerUtilsByModal.getAnswerResult();
    let answerData = answerResult.result;
    if (answerResult.flag) {
      const { appCheckList, userTagCheckList, type, answerIndex, slotValues, slotDetailList } = this.state;
      answerData.userTagIdList = userTagCheckList;
      answerData.robotList = appCheckList;

      if (slotDetailList.length > 0) {
        // 判断词槽是否全都为空
        let arr = slotDetailList.filter(item => item.isEnum);
        let arrSlot = arr.map(item => item.id);
        let slotValuesCheck = slotValues.filter(item => item.values.length > 0);
        if (arr.length > 0 && slotValuesCheck.length < slotValues.length) {
          // 说明所有词槽的词槽值都为空
          message.error('词槽答案词槽值不能为空，请选择词槽');
          return false;
        }
      }

      // 判断用户标签是否全部为空
      if (userTagCheckList.length === 0) {
        message.error('用户标签不能为空');
        return false;
      };
      // 判断应用名称是否全部为空
      if (appCheckList.length === 0) {
        message.error('应用名称不能为空');
        return false;
      };

      answerData.slotValues = slotValues;
      if (type === 'edit') {
        this.props.answerSubmit(answerData, type, answerIndex);
      };
      if (type === 'add') {
        this.props.answerSubmit(answerData, type);
      };

      this.cancelModal()
    } else {
      if (answerResult.message) {
        message.error(answerResult.message);
      };
      return false
    }
  }

  cancelModal = () => {
    this.setState({
      visible: false,
      appList: [],
      userTagList: [],
      appCheckList: [{ robotId: 'all', robotName: '全部应用' }],
      userTagCheckList: [{ id: 'all', tagName: '全部标签' }],
      type: 'add',
      answerIndex: 0,
      slotDetailList: [],
      slotValues: []
    })
  }

  render() {
    const { visible, userTagList, appList, appCheckList, userTagCheckList, slotDetailList, slotValues } = this.state;
    const { form, slotData } = this.props;
    const getSlotValue = slot => {
      const { slotValues } = this.state;
      const slotIndex = slotValues.findIndex(item => item.id === slot.id)
      if (slotIndex === -1) {
        return []
      } else {
        return slotValues[slotIndex].values
      }
    };

    return (
      <Modal
        visible={visible}
        title='添加/编辑答案'
        onCancel={this.cancelModal}
        width={700}
        onOk={this.okModal}
        destroyOnClose={true}
        wrapClassName="updateAnswer"
        cancelButtonProps={{ ghost: true, type: 'primary' }}
      >
        {/**词槽条件：1.没有词槽不展示该项；2.isEnum是否是可枚举，不可枚举不支持设置条件*/}
        {
          slotDetailList.length > 0 ? (
            <div style={{ display: 'flex' }}>
              <label style={{ width: '70px', lineHeight: '32px' }}>词槽条件：</label>
              <div style={{ width: 'calc(100% - 70px)' }}>
                {
                  slotDetailList.map((item, index) => {
                    return (
                      <div key={index} style={item.name.length > 24 ? { marginBottom: 24 } : { marginBottom: 24, display: 'flex' }}>
                        <label style={{ lineHeight: '32px' }}>&lt;{item.name}&gt;=</label>
                        {
                          item.isEnum ? (
                            <Select suffixIcon={<Icon type="clock-circle" />} className="slotSelect" mode="multiple" style={item.name.length > 24 ? { width: '100%' } : { flex: 1 }} value={getSlotValue(item)} onChange={(values, option) => this.changeSlot(values, option, item)}>
                              <Select.Option value={'全部词槽'} item={{ id: '全部词槽', name: '全部词槽' }}>全部词槽</Select.Option>
                              {
                                item.items.map(slotItem => {
                                  return (
                                    <Select.Option value={slotItem.word} key={slotItem.id} item={item}>{slotItem.word}</Select.Option>
                                  )
                                })
                              }
                            </Select>
                          ) : '词槽值不可枚举，不支持设置条件'
                        }
                      </div>
                    )
                  })
                }
              </div>
            </div>
          ) : ''
        }
        <div style={{ marginBottom: 24, display: 'flex' }}>
          <label style={{ lineHeight: '32px' }}>&lt;{'应用名称'}&gt;=</label>
          <Select suffixIcon={<Icon type="clock-circle" />} className="appSelect" mode="multiple" value={appCheckList.map(item => item.robotId)} style={{ flex: 1 }} onChange={(values, option) => this.changeApp(values, option)}>
            <Select.Option value={'all'} item={{ id: 'all', name: '全部应用' }}>全部应用</Select.Option>
            {
              appList.map(item => {
                return (
                  <Select.Option value={item.robotId} key={item.robotId} item={item}>{item.name}</Select.Option>
                )
              })
            }
          </Select>
        </div>
        <div style={{ marginBottom: 24, display: 'flex' }}>
          <label style={{ lineHeight: '32px' }}>&lt;{'用户标签'}&gt;=</label>
          <Select suffixIcon={<Icon type="clock-circle" />} className="tagSelect" mode="multiple" value={userTagCheckList.map(item => item.id)} style={{ flex: 1 }} onChange={(values, option) => this.changeTag(values, option)}>
            <Select.Option value={'all'} item={{ id: 'all', tagName: '全部标签' }}>全部标签</Select.Option>
            {
              userTagList.map(item => {
                return (
                  <Select.Option value={item.id} key={item.id} item={item}>{item.tagName}</Select.Option>
                )
              })
            }
          </Select>
        </div>
        <Form>
          <AnswerUtils form={form} onRef={ref => this.AnswerUtilsByModal = ref} hasRefer={true} />
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(UpdateAnswerModal)